package com.wcl.nullmusic.utils;

import java.lang.ref.WeakReference;

import android.os.Handler;
import android.os.Message;

import com.wcl.nullmusic.ui.fragment.RecommendFragment;

public class ImageHandler extends Handler{  
    
    /** 
     * 请求更新显示的View
     */  
    public static final int MSG_UPDATE_IMAGE  = 1;
    /** 
     * 请求更新暂停轮播
     */  
    public static final int MSG_KEEP_SILENT   = 2;
    /** 
     * 请求恢复轮播
     */  
    public static final int MSG_BREAK_SILENT  = 3;
    /** 
     * 记录最新页号,当用户手动滑动时需要记录新页号,否则会使轮播的页面出错
     */  
    public static final int MSG_PAGE_CHANGED  = 4;
       
    //轮播时间的间隔
    public static final long MSG_DELAY = 4000;
       
    //使用弱引用,避免Handler泄露,泛型参数可以不是Activity,Fragment也可以
    private WeakReference<RecommendFragment> weakReference;
    private int currentItem = 0;  
       
    public ImageHandler(WeakReference<RecommendFragment> wk){
        weakReference = wk;  
    }  
       
    @Override  
    public void handleMessage(Message msg) {  
        super.handleMessage(msg);  
//        Log.d(LOG_TAG, "receive message " + msg.what);  
        RecommendFragment fragment = weakReference.get();
        if (fragment==null){
            //被回收,无需处理UI
            return ;  
        }  
        //检查消息队列兵一处未发送的消息,这主要是避免在复杂环境下消息出现重估等问题
        if (fragment.handler.hasMessages(MSG_UPDATE_IMAGE)){
            fragment.handler.removeMessages(MSG_UPDATE_IMAGE);
        }  
        switch (msg.what) {  
        case MSG_UPDATE_IMAGE:  
            currentItem++;
            fragment.viewPager.setCurrentItem(currentItem);
            // 准备下次播放
            fragment.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
            break;  
        case MSG_KEEP_SILENT:  
            // 只要不发送消息就暂停
            break;  
        case MSG_BREAK_SILENT:
            fragment.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
            break;  
        case MSG_PAGE_CHANGED:  
            // 记录当前的页号,避免播放的时候页面显示不正确
            currentItem = msg.arg1;  
            break;  
        default:  
            break;  
        }   
    }  
}